package com.teliasonera.crm.testing;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class CustomersPage extends CRMPage {

    public final static String KEY_CUSTOMER_NAME = "_idJsp2_CustomTable_WAR_CustomTable_INSTANCE_Hkki_:_id1_CustomTable_WAR_CustomTable_INSTANCE_Hkki_";
    
    private final static String SEARCH_BUTTON = "_idJsp2_CustomTable_WAR_CustomTable_INSTANCE_Hkki_:_id12_CustomTable_WAR_CustomTable_INSTANCE_Hkki_";
    private final static String CLEAR_BUTTON = "_idJsp2_CustomTable_WAR_CustomTable_INSTANCE_Hkki_:_id13_CustomTable_WAR_CustomTable_INSTANCE_Hkki_";
    private final static String SEARCH_RESULT_LAST = "//table[contains(@class, 'data customtable')]/tbody/tr[contains(@class, 'last')]/td/a";

    public CustomersPage(WebDriver newDriver) {
        super(newDriver, PAGE_TITLE_CUSTOMERS);
    }

    public void searchForCustomers(Map searchParameters) {
        log("Search for customers");
        
        driver.findElement(By.id(CLEAR_BUTTON)).click();
        waitForPageToLoad(10);
        
        Set set = searchParameters.entrySet();
        Iterator i = set.iterator();

        while (i.hasNext()) {
            Map.Entry me = (Map.Entry) i.next();
            driver.findElement(By.id((String) me.getKey())).sendKeys((String) me.getValue());
        }

        driver.findElement(By.id(SEARCH_BUTTON)).click();

    }

    public void clickCustomerSearch(int result) {
        waitForPageToLoad(10);
        driver.findElement(By.id("_idJsp2_CustomTable_WAR_CustomTable_INSTANCE_Hkki_:dataScroller_CustomTable_WAR_CustomTable_INSTANCE_Hkki_:" + result + ":_id22_CustomTable_WAR_CustomTable_INSTANCE_Hkki_")).click();
    }
    
    public boolean checkCurrentCustomer(String customerName) {
        
        String searchPattern = "//div/div[text()[contains(.,'" + customerName + "')]]";
        log("Check current customer :" + searchPattern);
        
        return isElementPresent(By.xpath(searchPattern));
    }
    
}